package wang.hu.bos.realm;

import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import wang.hu.bos.dao.system.PermissionDao;
import wang.hu.bos.dao.system.RoleDao;
import wang.hu.bos.domain.system.Permission;
import wang.hu.bos.domain.system.Role;
import wang.hu.bos.domain.system.User;
import wang.hu.bos.service.system.UserService;

//@Service("bosRealm")
public class BosRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private PermissionDao permissionDao;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		System.out.println("用戶角色授權方法執行————————————————————————————");
		SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		Set<Role> roles = user.getRoles();
		for (Role role : roles) {
			authenticationInfo.addRole(role.getKeyword());
			Set<Permission> permissions = role.getPermissions();
			for (Permission permission : permissions) {
				authenticationInfo.addStringPermission(permission.getKeyword());
			}
		}

		return authenticationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		System.out.println("用戶登陸認證方法執行————————————————————————————");
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		User user = userService.findByUsername(usernamePasswordToken
				.getUsername());
		if (user == null) {
			return null;
		} else {
			return new SimpleAuthenticationInfo(user, user.getPassword(),
					getName());
		}
	}

}
